//
//  PlayerBarView.m
//  ZYTS-iPhone
//
//  Created by fred on 1/8/13.
//  Copyright (c) 2013 wzyk. All rights reserved.
//

#import "PlayerBarView.h"
#import "AudioPlayer.h"
#import "PlayerViewController.h"

@implementation PlayerBarView

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePlayerBar) name:kPlayerStateDidChange object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playingIndexDidChange) name:kPlayerIndexDidChange object:nil];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    titleLabel.pauseInterval = 0;
    [self updatePlayerBar];
    [self playingIndexDidChange];
}

- (void)updatePlayerBar
{
    NSDictionary *item = [[AudioPlayer defaultPlayer] currentItem];
    
    if (item != nil) {
        NSString *title = [NSString stringWithFormat:@"%@ %@",[item valueForKey:@"item_name"],[item valueForKey:@"sub_name"]];
        if (![[titleLabel text] isEqualToString:title]) {
            [titleLabel setText:title];
        }
    }
    else {
        [titleLabel setText:@"当前没有播放列表"];
    }
    
    switch ([[AudioPlayer defaultPlayer] playerState]) {
        case AudioPlayerStatePlaying:
            [playBtnIB setBackgroundImage:[UIImage imageNamed:@"player_play_stop"] forState:UIControlStateNormal];
            break;
        case AudioPlayerStateStoped:
            [playBtnIB setBackgroundImage:[UIImage imageNamed:@"player_play"] forState:UIControlStateNormal];
            break;
        case AudioPlayerStateNone:
            break;
        default:
            break;
    }
}

- (void)playingIndexDidChange
{
    lastButton.enabled = ([[AudioPlayer defaultPlayer] playingIndex] != 0);
    nextButton.enabled = ([[AudioPlayer defaultPlayer] playingIndex] != [[[AudioPlayer defaultPlayer] playlist] count] - 1);
}

- (IBAction)clickFisrtBtnIB:(id)sender
{
    [[AudioPlayer defaultPlayer] playPrevious];
}

- (IBAction)clickPlayBtnIB:(id)sender
{
    [[AudioPlayer defaultPlayer] play];
}

- (IBAction)clickLastBtnIB:(id)sender
{
    [[AudioPlayer defaultPlayer] playNext];
}

- (IBAction)clickGotoBtnIB:(id)sender
{
    PlayerViewController *playerViewController = [[[PlayerViewController alloc] initWithNibName:@"PlayerViewController" bundle:nil] autorelease];
    UINavigationController *navController = (UINavigationController *)self.window.rootViewController;
    [navController pushViewController:playerViewController animated:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [playBtnIB release];
    [titleLabel release];
    [lastButton release];
    [nextButton release];
    [super dealloc];
}
@end
